/**
 * 
 */
var currentTh;
gaugeThs = window.parent.gaugeThs;
var thList;
var dropListTimeout;
$(function() {
	searchStart(1);
	console.log(gaugeThs)
	$(".toolbar-item").hover(function() {
		hoverOnToolbarItem($(this));
	}, function() {
		$(".toolbar-tip").remove();
	});
	$(".gauge-th").each(function() {
		$(this).click(function() {
			gaugeThClick($(this))
		});
	})
	$("#allGauges").click(function(){searchStart(1);});
	$("#needToCalibrateThisMonth").click(searchInputButtonClick);
	$("#expired").click(searchInputButtonClick);
	$("#lost").click(searchInputButtonClick);
	$("#scrapped").click(searchInputButtonClick);
	
	
	
	$("#search_input_button").click(searchInputButtonClick)
	$("#search_date_button").click(searchDateButtonClick)
	$("#search_date").click(searchDateClick)
	$("#dropList").change(dropListChange);
	// 表头选择框失去焦点后隐藏

	$("#dropList").blur(function(e) {
		dropListTimeout = setTimeout(function() {
			closeSearchItem();
		}, 200)

	});

	$("#search_input input").blur(function(e) {
		dropListTimeout = setTimeout(function() {
			closeSearchItem();
		}, 200)
	});
	$("#search_date_start").blur(function(e) {
		var searchDateEnd = $("#search_date_end");
		if (!searchDateEnd.is(":focus")) {
			dropListTimeout = setTimeout(function() {
				closeSearchItem();
			}, 200)

		}

	});
	$("#search_date_end").blur(function(e) {
		var searchDateEnd = $("#search_date_start");
		if (!searchDateEnd.is(":focus")) {
			dropListTimeout = setTimeout(function() {
				closeSearchItem();
			}, 200)

		}

	});

	$("#remove-gauge").click(function() {
		removeGauge();
	});
	$("#edit-gauge").click(function() {
		getGaugeTypeAndDepartmentInfo(this.id);
	});
	$("#add-gauge").click(function() {
		getGaugeTypeAndDepartmentInfo(this.id);
	});
	$("#search-gauge").click(function() {
		getGaugeTypeAndDepartmentInfo(this.id);
	});

	$("#add-gauge-modal").on('show.bs.modal', function() {
		$("#add-gauge-form").find("input,select,#gaugeRemark").each(function() {
			$(this).change(function() {
				if ($("#save-button").hasClass("disabled")) {
					$("#save-button").removeClass("disabled");
				}
			})
		});
	});

	$("#add-gauge-modal").on('hidden.bs.modal', function() {
		$("#save-button").addClass("disabled");
		emptySelect(this.id);
		var form = document.getElementById("add-gauge-form");
		form.reset();
		searchStart(1);
	});
	$("#search-modal").on('hidden.bs.modal', function(event) {
		emptySelect(this.id);
	});

	$("#save-button").click(function() {
		if (!$(this).hasClass("disabled")) {

			$("#add-gauge-submit").click()
		}
	});

})

function emptySelect(id) {
	var gaugeName = $("#gaugeName");
	var department = $("#department");
	if (id == "search-modal") {
		gaugeName = $("#searchGaugeName");
		department = $("#searchDepartment");
	}
	gaugeName.empty();
	department.empty();

}

function removeGauge() {
	var gauges = $(".gauge-selected")
	var ids = "";
	var gaugeNums = "";
	if (gauges.length < 1) {
		alert("请至少选择一项!");
		return;
	} else if (gauges.length > 0) {
		for (var i = 0; i < gauges.length; i++) {
			ids += gauges.eq(i).find("#td-id").text() + ",";
			gaugeNums += gauges.eq(i).find("#td-gaugeNum").text() + "\n";
		}
	}
	ids = ids.substr(0, ids.length - 1);
	var result = confirm("你确定要删除以下:\n" + gaugeNums + gauges.length + "个量具吗?");
	if (result) {
		$.post("removeGauge.do", {
			gaugeIds : ids
		}, function(data) {
			var data = JSON.parse(data);
			if (data.status == "s") {
				alert("成功删除" + data.result + "条数据!");
				searchStart(1);
			} else {
				alert("删除出错!");
			}
		})

	}
}

function addGauge() {
	var id = $("#id").val();
	var gaugeNum = $("#gaugeNum").val();
	var gaugeNameAbbr = $("#gaugeName").val();
	var gaugeName = $("#gaugeName option:selected").text();
	var gaugeSpecification = $("#gaugeSpecification").val();
	var gaugeAccuracy = $("#gaugeAccuracy").val();
	var gaugeModel = $("#gaugeModel").val();
	var gaugeManufacturer = $("#gaugeManufacturer").val();
	var dateOfAcceptance = $("#dateOfAcceptance").val();
	var gaugeFolder = $("#gaugeFolder").val();
	var dateOfLastCalibration = $("#dateOflastCalibration").val();
	var calibrationResult = $("#calibrationResult option:selected").text();
	var gaugeCalibratePeriod = $("#gaugeCalibratePeriod").val();
	var gaugeStatus = $("#gaugeStatus option:selected").text();
	var gaugeOwner = $("#gaugeOwner").val();
	var departmentNum = $("#department").val();
	var department = $("#department option:selected").text();
	var gaugeRemark = $("#gaugeRemark").val();
	var gauge = {
		id : id,
		gaugeNum : gaugeNum,
		gaugeName : gaugeName,
		gaugeNameAbbr : gaugeNameAbbr,
		gaugeSpecification : gaugeSpecification,
		gaugeAccuracy : gaugeAccuracy,
		gaugeModel : gaugeModel,
		gaugeManufacturer : gaugeManufacturer,
		dateOfAcceptance : dateOfAcceptance,
		gaugeFolder : gaugeFolder,
		dateOfLastCalibration : dateOfLastCalibration,
		calibrationResult : calibrationResult,
		gaugeCalibratePeriod : gaugeCalibratePeriod,
		gaugeStatus : gaugeStatus,
		gaugeOwner : gaugeOwner,
		departmentNum : departmentNum,
		department : department,
		gaugeRemark : gaugeRemark
	}
	var url;
	var title = $("#add-gauge-modal").find('.modal-title').text();
	if (title == "新增") {
		url = "addGauge.do";
	} else if (title == "编辑") {

		url = "editGauge.do";
	}

	$.post(url, gauge, function(data) {
		var data = JSON.parse(data);
		alert(data.info);
		if (data.status == "s") {
			$("#add-gauge-modal").modal("hide");
		}
	})

}

function hoverOnToolbarItem(obj) {
	var top = obj.offset().top;
	var left = obj.offset().left;
	var tip = "<div class='toolbar-tip'>" + obj.attr("tip") + "</div>";
	$("body").append(tip);
	var toolbarTip = $(".toolbar-tip");
	toolbarTip.css({
		"position" : "absolute",
		"top" : top + "px",
		"left" : (left) + "px",
		"border-radius" : "5px"
	});
	if (!toolbarTip.is(":animated")) {

		toolbarTip.animate({
			"left" : (left - 50) + "px",
			"display" : "block"
		});
	}
}

function getGaugeTypeAndDepartmentInfo(id) {
	var gaugeName = $("#gaugeName");
	var department = $("#department");
	$("#gaugeNum").attr("disabled", false);
	if (id == "add-gauge") {
		$("#add-gauge-modal").find('.modal-title').text("新增");
	} else if (id == "edit-gauge") {
		var length = $(".gauge-selected").length;
		if (length == 0) {
			alert("请选择一项进行编辑!");
			return;
		} else if (length > 1) {
			alert("最多只能选择一项进行编辑!");
			return;
		}
		$("#add-gauge-modal").find('.modal-title').text("编辑")
	} else if (id == "search-gauge") {
		gaugeName = $("#searchGaugeName");
		department = $("#searchDepartment");
	}

	$.post("getGaugeTypeAndDepartmentInfo.do", function(data) {

		var data = JSON.parse(data);

		for ( let k in data[0]) {
			var element = "<option value='" + data[0][k] + "'>" + k + "</option>"
			gaugeName.append(element);
		}
		for ( let key in data[1]) {
			var element = "<option value='" + data[1][key] + "'>" + key + "</option>"
			department.append(element);
		}

		if (id == "edit-gauge") {
			var gauge = $(".gauge-selected").children("td");
			$("#gaugeNum").val(gauge.eq(5).text());
			$("#gaugeNum").attr("disabled", true);
			$("#gaugeName option:contains(" + gauge.eq(2).text() + ")").attr("selected", true);
			$("#gaugeSpecification").val(gauge.eq(3).text());
			$("#gaugeAccuracy").val(gauge.eq(4).text());
			$("#gaugeModel").val(gauge.eq(6).text());
			$("#gaugeManufacturer").val(gauge.eq(7).text());
			$("#dateOfAcceptance").val(gauge.eq(8).text());
			$("#gaugeFolder").val(gauge.eq(17).text());
			$("#dateOflastCalibration").val(gauge.eq(9).text());
			$("#calibrationResult option:contains(" + gauge.eq(10).text() + ")").attr("selected", true);
			$("#gaugeCalibratePeriod").val(gauge.eq(16).text());
			$("#gaugeStatus option:contains(" + gauge.eq(13).text() + ")").attr("selected", true);
			$("#gaugeOwner").val(gauge.eq(14).text());
			$("#department option:contains(" + gauge.eq(15).text() + ")").attr("selected", true);
			$("#gaugeRemark").val(gauge.eq(18).text());
			$("#id").val(gauge.eq(19).text());

		}

		if (id == "search-gauge") {
			$("#search-modal").modal("show");

		} else {

			$("#add-gauge-modal").modal("show");
		}

	});

}

function searchGauge(target) {

	var width = target.outerWidth();
	var height = target.outerHeight();
	var x = target.offset().left;
	var y = target.offset().top;
	target.find("span").removeClass("glyphicon-triangle-bottom");
	target.find("span").addClass("glyphicon-triangle-top");

	var item;
	var target = target[0];
	if (target.id == "th-aceNum" || target.id == "th-gaugeNum") {
		item = $("#search_input");
		if (gaugeThs[target.id.substr(3)] == undefined) {
			gaugeThs[target.id.substr(3)] = "";
		}

		$("#search_input_box").val(gaugeThs[target.id.substr(3)]);

	} else if (target.id == "th-dateOfAcceptance" || target.id == "th-dateOfLastCalibration" || target.id == "th-dateOfNextCalibration") {
		if (gaugeThs[target.id.substr(3) + "_start"] == undefined) {
			gaugeThs[target.id.substr(3) + "_start"] = "";
		}
		if (gaugeThs[target.id.substr(3) + "_end"] == undefined) {
			gaugeThs[target.id.substr(3) + "_end"] = "";
		}
		item = $("#search_date");
		$("#search_date_start").val(gaugeThs[target.id.substr(3) + "_start"]);
		$("#search_date_end").val(gaugeThs[target.id.substr(3) + "_end"]);
	} else {
		item = $("#dropList");
		item.empty();
		if (gaugeThs[target.id.substr(3)] == undefined) {
			gaugeThs[target.id.substr(3)] = "123456";
		}
		var option = "<option value='123456'>未选择</option>"
		item.append(option);
		$.post("getThDropList.do", {
			thName : target.id.substr(3)
		}, function(data) {
			var gaugeTypeList = JSON.parse(data);
			console.log(gaugeTypeList);
			var k;
			for (k in gaugeTypeList) {
				var option = "<option value=" + k + ">" + gaugeTypeList[k] + "</option>"
				item.append(option);
			}
			item.val(gaugeThs[target.id.substr(3)]);
		})

	}

	item.css({
		width : width + "px",
		position : "absolute",
		top : y + parseInt(height) + "px",
		left : x + "px"

	})

	item.show();

	currentTh = target.id.substr(3);
	if (target.id == "th-aceNum" || target.id == "th-gaugeNum") {
		item.find("input").focus();
	} else if (target.id == "th-dateOfAcceptance" || target.id == "th-dateOfLastCalibration" || target.id == "th-dateOfNextCalibration") {
		$("#search_date_start").focus();
	} else {

		item.focus();
	}
	

}

function closeSearchItem() {

	var dropList = $("#dropList").hide();
	var search_input = $("#search_input").hide();
	var search_date = $("#search_date").hide();
	trianleToBottom();

}

function trianleToBottom() {

	$(".gauge-th").each(function() {
		var span = $(this).find("span");
		span.removeClass("glyphicon-triangle-top");
		span.addClass("glyphicon-triangle-bottom");
	})
}

function getThList() {
	console.log("1");
	$.post("getThList.do", {}, function(data) {
		thList = JSON.parse(data);
	});
}

/*function getAllGauges() {
	$.post("getAllGaugesByPost.do", {}, function(data) {
		var gaugeList = JSON.parse(data);
		var tbody = $("#tbody-allGauges");
		for (var i = 0; i < gaugeList.length; i++) {
			var gauge = "<tr class='gauges'>" + "<td>" + (i + 1) + "</td>" + "<td id='td-aceNum'>" + gaugeList[i]["aceNum"] + "</td>" + "<td id='td-gaugeName'>"
					+ gaugeList[i]["gaugeName"] + "</td>" + "<td id='td-gaugeSpecification'>" + gaugeList[i]["gaugeSpecification"] + "</td>" + "<td id='td-gaugeAccuracy'>"
					+ gaugeList[i]["gaugeAccuracy"] + "</td>" + "<td id='td-gaugeNum'>" + gaugeList[i]["gaugeNum"] + "</td>" + "<td id='td-gaugeModel'>"
					+ gaugeList[i]["gaugeModel"] + "</td>" + "<td id='td-gaugeManufacturer'>" + gaugeList[i]["gaugeManufacturer"] + "</td>" + "<td id='td-dateOfAcceptance'>"
					+ gaugeList[i]["dateOfAcceptance"] + "</td>" + "<td id='td-dateOfLastCalibration'>" + gaugeList[i]["dateOfLastCalibration"] + "</td>"
					+ "<td id='td-calibrationResult'>" + gaugeList[i]["calibrationResult"] + "</td>" + "<td id='td-dateOfNextCalibration'>" + gaugeList[i]["dateOfNextCalibration"]
					+ "</td>" + "<td id='td-gaugeRemainingDays'>" + gaugeList[i]["gaugeRemainingDays"] + "</td>" + "<td id='td-gaugeStatus'>" + gaugeList[i]["gaugeStatus"]
					+ "</td>" + "<td id='td-gaugeOwner'>" + gaugeList[i]["gaugeOwner"] + "</td>" + "<td id='td-department'>" + gaugeList[i]["factory"] + "-"
					+ gaugeList[i]["department"] + "</td>" + "<td id='td-gaugeCalibratePeriod'>" + gaugeList[i]["gaugeCalibratePeriod"] + "</td>" + "<td id='td-gaugeFolder'>"
					+ gaugeList[i]["gaugeFolder"] + "</td>" + "<td id='td-gaugeRemark'>" + gaugeList[i]["gaugeRemark"] + "</td>" + "<td id='td-id' style='display: none;'>"
					+ gaugeList[i]["id"] + "</td>" + "<td></td>" + "</tr>"

			tbody.append(gauge);
		}

		// 为上面添加的gauge添加click事件
		$(".gauges").each(function() {
			$(this).click(function() {
				console.log("12")
				if ($(this).hasClass("gauge-selected")) {
					$(this).removeClass("gauge-selected");

				} else {
					$(this).addClass("gauge-selected");

				}
			})
		})
	})
}*/

// 下拉列表选择事件
function dropListChange() {
	var selected = $(this).val();
	gaugeThs[currentTh] = selected;

	console.log($("#" + currentTh));
	if (selected == "123456") {
		$("#th-" + currentTh).removeClass("th-selected");
	} else {
		$("#th-" + currentTh).addClass("th-selected");
	}
	console.log(gaugeThs);
	closeSearchItem();
	searchStart(1);
}

function gaugeThClick(target) {

	clearTimeout(dropListTimeout);
	var dropList = $("#dropList");
	var search_input = $("#search_input");
	var search_date = $("#search_date");
	if (dropList.is(":visible") || search_input.is(":visible") || search_date.is(":visible")) {
		closeSearchItem();
	} else {
		searchGauge(target)

	}

}

function searchInputButtonClick() {
	clearTimeout(dropListTimeout);
	var aceNum = $("#search_input_box").val();
	gaugeThs[currentTh] = aceNum;
	if (aceNum == "") {
		$("#th-" + currentTh).removeClass("th-selected");
	} else {
		$("#th-" + currentTh).addClass("th-selected");
	}
	searchStart(1);
	closeSearchItem();
}

function searchStart(page_num) {
	gaugeThs["pageNum"] = page_num;
	$.post("searchGauge.do", gaugeThs, function(data) {
		var gaugeList = JSON.parse(data);
		var page = gaugeList[0];
		var baseNum = (page.currentPage - 1) * page.eachPageCount;
		console.log(gaugeList);
		var tbody = $("#tbody-allGauges");
		tbody.empty();
		for (var i = 1; i < gaugeList.length; i++) {
			var gauge = "<tr class='gauges'>" + "<td>" + (i + baseNum) + "</td>" + "<td id='td-aceNum'>" 
					+ gaugeList[i]["aceNum"] + "</td>" + "<td id='td-gaugeName'>"
					+ gaugeList[i]["gaugeName"] + "</td>" + "<td id='td-gaugeSpecification'>" 
					+ gaugeList[i]["gaugeSpecification"] + "</td>" + "<td id='td-gaugeAccuracy'>"
					+ gaugeList[i]["gaugeAccuracy"] + "</td>" + "<td id='td-gaugeNum'>" 
					+ gaugeList[i]["gaugeNum"] + "</td>" + "<td id='td-gaugeModel'>"
					+ gaugeList[i]["gaugeModel"] + "</td>" + "<td id='td-gaugeManufacturer'>" 
					+ gaugeList[i]["gaugeManufacturer"] + "</td>" + "<td id='td-dateOfAcceptance'>"
					+ gaugeList[i]["dateOfAcceptance"] + "</td>" + "<td id='td-dateOfLastCalibration'>" 
					+ gaugeList[i]["dateOfLastCalibration"] + "</td>"+ "<td id='td-calibrationResult'>" 
					+ gaugeList[i]["calibrationResult"] + "</td>"+ "<td id='td-dateOfNextCalibration'>" 
					+ gaugeList[i]["dateOfNextCalibration"]+ "</td>" + "<td id='td-gaugeRemainingDays'>" 
					+ gaugeList[i]["gaugeRemainingDays"]+ "</td>" + "<td id='td-gaugeStatus'>" 
					+ gaugeList[i]["gaugeStatus"]+ "</td>" + "<td id='td-gaugeOwner'>" 
					+ gaugeList[i]["gaugeOwner"] + "</td>"+ "<td id='td-department'>" 
					+ gaugeList[i]["factory"] + "-"
					+ gaugeList[i]["department"] + "</td>" + "<td id='td-gaugeCalibratePeriod'>" 
					+ gaugeList[i]["gaugeCalibratePeriod"] + "</td>" + "<td id='td-gaugeFolder'>"
					+ gaugeList[i]["gaugeFolder"] + "</td>" + "<td id='td-gaugeRemark'>" 
					+ gaugeList[i]["gaugeRemark"] + "</td>" + "<td id='td-id' style='display: none;'>"
					+ gaugeList[i]["id"] + "</td>" + "<td></td>" + "</tr>"
			tbody.append(gauge);
		}

		// 为上面添加的gauge添加click事件
		$(".gauges").each(function() {
			$(this).click(function() {
				console.log("12")
				if ($(this).hasClass("gauge-selected")) {
					$(this).removeClass("gauge-selected");

				} else {
					$(this).addClass("gauge-selected");

				}
			})
		})

		var pagination = $("#pagination");
		pagination.empty();

		var first = "<li id='first_page' page_num='1'><a class='btn btn-default' href='#' role='button'>首页</a></li>"
		var previous = "<li id='previous_page'><a href='#' aria-label='Previous'> <span aria-hidden='true'>&laquo;</span></a></li>"
		pagination.append(first);
		pagination.append(previous);
		
		for (var i = page.currentPage - 2,j=i; i <= page.totalPage; i++) {
			
			if (i < 1){
				i = 1;
				j=i;
			}else if(page.totalPage-j<=4 && page.totalPage>5){
				i=page.totalPage-4;
				j=0;
			}
			var li = "<li class='page_number' page_num=" + i + "><a href='javascript:void(0)'>" + i + "</a></li>"
			pagination.append(li);
			if (page.currentPage >= 3) {
				if (i == page.currentPage + 2)
					break;
			} else {
				if (i == 5)
					break;
			}
		}
		
		
		
		
		pagination.find(".page_number").removeClass("active");
		pagination.find(".page_number[page_num='" + page.currentPage + "']").addClass("active");
		var next = "<li id='next_page'><a href='#' aria-label='Next'> <span aria-hidden='true'>&raquo;</span></a></li>";
		var last = "<li id='last_page' page_num=" + page.totalPage + "><a class='btn btn-default' href='#' role='button'>尾页</a></li>"
		pagination.append(next);
		pagination.append(last);

		if (page.currentPage == 1) {
			$("#first_page").addClass("disabled")
			$("#previous_page").addClass("disabled")
		} else {
			$("#first_page").removeClass("disabled")
			$("#previous_page").removeClass("disabled")
		}
		if (page.totalPage == page.currentPage) {

			$("#next_page").addClass("disabled")
			$("#last_page").addClass("disabled")
		} else {
			$("#next_page").removeClass("disabled")
			$("#last_page").removeClass("disabled")
		}
		pagination.find("li").each(function() {
			$(this).click(function() {
				var currentPage;
				if ($(this).attr("id") == "previous_page") {
					currentPage = (page.currentPage - 1) < 1 ? 1 : page.currentPage - 1;
				} else if ($(this).attr("id") == "next_page") {
					currentPage = (page.currentPage + 1) > page.totalPage ? page.totalPage : page.currentPage + 1;

				} else {
					currentPage = $(this).attr("page_num");
				}
				searchStart(currentPage);
			})
		})

	})
}

function searchDateButtonClick() {
	var dateStart = $("#search_date_start").val();
	var dateEnd = $("#search_date_end").val();
	gaugeThs[currentTh + "_start"] = dateStart;
	gaugeThs[currentTh + "_end"] = dateEnd;
	gaugeThs[currentTh] = dateStart + "to" + dateEnd;
	if (dateStart == "" && dateEnd == "") {
		// gaugeThs[currentTh]="to";
		$("#th-" + currentTh).removeClass("th-selected");
	} else {
		$("#th-" + currentTh).addClass("th-selected");
	}
	searchStart(1);
	closeSearchItem();
}

function searchDateClick() {
	clearTimeout(dropListTimeout);
}